package com.neusoft.hifly.message.msg.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.LongUtil;
import com.neusoft.hifly.commons.lang.StringConstants;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.core.log.annotation.LogType;
import com.neusoft.hifly.core.log.annotation.OperationLog;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.core.utils.GlobalConstants;
import com.neusoft.hifly.dynamicds.multi.annotation.MultiDynamicRoutingDataSource;
import com.neusoft.hifly.message.msg.dao.IMsgDao;
import com.neusoft.hifly.message.msg.entity.MsgInboxObj;
import com.neusoft.hifly.message.msg.entity.MsgObj;
import com.neusoft.hifly.message.msg.service.IMsgInboxService;
import com.neusoft.hifly.message.msg.service.IMsgService;

/**
 * Title: 消息服务
 * <p>
 * Description: 站内信 Service
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
@MultiDynamicRoutingDataSource
public class MsgServiceImpl extends CTSaaSBaseServiceImpl implements IMsgService {
	@Autowired(required = false)
	private IMsgDao msgDao;
	@Autowired(required = false)
	private IMsgInboxService msgInboxService;

	/**
	 * 保存对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param obj
	 *            对象
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	@OperationLog(method = LogType.UPDATE, msg = "站内信")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void saveOrUpdate(final String organCode, final long organLogicId, final MsgObj obj)
			throws SystemErrorException {
		if (StringUtils.isEmpty(organCode) || obj == null) {
			return;
		}

		if (StringUtils.isEmpty(StringUtils.trimToEmpty(obj.getContent()))) {
			throw new SystemErrorException("内容不能为空!");
		}

		final MsgObj oldObj = msgDao.getByLogicId(organCode, organLogicId, obj.getLogicId(), false);

		obj.setOrganLogicId(organLogicId);

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存

			obj.setId(idWorker.nextId());
			if (GlobalConstants.ABS_ID != obj.getLogicId()) {
				obj.setLogicId(idWorker.nextId());
			}
			obj.setUpdateTime(LocalDateTime.now());

			if (StringUtils.isEmpty(obj.getUpdatePerson())) {
				obj.setUpdatePerson(TokenContextHolder.get().getUserName());
			}

			this.setForm(obj, obj);

			// 发送时间
			obj.setSendTime(LocalDateTime.now());
			// 发件人ID
			if (LongUtil.isEmpty(obj.getUserId())) {
				obj.setUserId(TokenContextHolder.get().getUserLogicId());
			}
			// 发件人姓名
			if (StringUtils.isEmpty(obj.getUserName())) {
				obj.setUserName(TokenContextHolder.get().getUserName());
			}

			msgDao.insert(obj);

			// 根据接收人、接收人ID发送未读消息
			msgInboxService.saveMsgboxHave(organCode, organLogicId, obj.getReceiveUsers(), obj);

		} else {
			// 更新

			this.setForm(obj, oldObj);

			oldObj.setUpdateTime(LocalDateTime.now());
			if (StringUtils.isEmpty(oldObj.getUpdatePerson())) {
				oldObj.setUpdatePerson(TokenContextHolder.get().getUserName());
			}

			msgDao.updateById(oldObj);

		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象ID
	 */
	@Override
	@OperationLog(method = LogType.DELETE, msg = "站内信")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByLogicId(final String organCode, final long organLogicId, final long logicId) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}

		msgDao.deleteByLogicId(organCode, organLogicId, logicId);

		// 级联删除个人消息记录
		final List<MsgInboxObj> msgInboxObjs = msgInboxService.findByMsgLogicId(organCode, organLogicId, logicId);
		if (msgInboxObjs != null) {
			for (final MsgInboxObj inObj : msgInboxObjs) {
				msgInboxService.deleteByLogicId(organCode, organLogicId, inObj.getLogicId());
			}
		}

	}

	/**
	 * 批量删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicIds
	 *            对象ID，多id使用英文逗号分隔
	 */
	@Override
	public void deleteByBatch(final String organCode, final long organLogicId, final String logicIds) {
		if (StringUtils.isEmpty(organCode) || StringUtils.isEmpty(logicIds)) {
			return;
		}
		final String[] logicIdArr = logicIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}
		for (final String logicId : logicIdArr) {
			if (StringUtils.isEmpty(logicId)) {
				continue;
			}
			this.deleteByLogicId(organCode, organLogicId, Long.parseLong(logicId));
		}
	}

	/**
	 * 删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param objLogicId
	 *            业务表单的ID
	 */
	@Override
	@OperationLog(method = LogType.DELETE, msg = "站内信")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByObjLogicId(final String organCode, final long organLogicId, final long objLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}
		msgDao.deleteByObjLogicId(organCode, organLogicId, objLogicId);
		msgInboxService.deleteByObjLogicId(organCode, organLogicId, objLogicId);
	}

	/**
	 * 根据id查询对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象logicId
	 * @return 对象
	 */
	@Override
	public MsgObj getByLogicId(final String organCode, final long organLogicId, final long logicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return msgDao.getByLogicId(organCode, organLogicId, logicId, false);
	}

	/**
	 * 根据逻辑id查询对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param logicId
	 *            对象logicId
	 * @param isGetReceiveNames
	 *            是否查看接收人信息
	 * @return 对象
	 */
	@Override
	public MsgObj getByLogicId(final String organCode, final long organLogicId, final long logicId,
			final boolean isGetReceiveNames) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return msgDao.getByLogicId(organCode, organLogicId, logicId, isGetReceiveNames);
	}

	/**
	 * 查询所有对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @return 对象集合
	 */
	@Override
	public List<MsgObj> findAll(final String organCode, final long organLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return msgDao.findAll(organCode, organLogicId);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 集合
	 */
	@Override
	public List<MsgObj> search(final String organCode, final long organLogicId, Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final QueryWrapper<MsgObj> queryWrapper = new QueryWrapper<MsgObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "SEND_TIME" });
		return msgDao.selectList(queryWrapper);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param offset
	 *            当前页数
	 * @param limit
	 *            分页长度
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 返回Map
	 */
	@Override
	public Map<String, Object> search(final String organCode, final long organLogicId, final int offset,
			final int limit, Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final com.baomidou.mybatisplus.plugins.Page<MsgObj> page = new com.baomidou.mybatisplus.plugins.Page<MsgObj>(
				offset, limit);

		final Map<String, Object> map = new HashMap<String, Object>(2);
		map.put(GlobalConstants.PAGE_RESULTS, msgDao.search(organCode, organLogicId, page, property));
		map.put(GlobalConstants.PAGE_COUNT, msgDao.count(organCode, organLogicId, property));
		return map;
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final MsgObj fromObj, final MsgObj toObj) {
		toObj.setOrganLogicId(fromObj.getOrganLogicId());
		toObj.setTitle(StringUtils.trimToEmpty(fromObj.getTitle()));
		toObj.setContent(StringUtils.trimToEmpty(fromObj.getContent()));
		toObj.setSendType(StringUtils.trimToEmpty(fromObj.getSendType()));
		toObj.setUserId(fromObj.getUserId());
		toObj.setUserName(StringUtils.trimToEmpty(fromObj.getUserName()));
		toObj.setSendTime(fromObj.getSendTime());
		toObj.setType(StringUtils.trimToEmpty(fromObj.getType()));
		toObj.setUrl(StringUtils.trimToEmpty(fromObj.getUrl()));
		toObj.setObjId(fromObj.getObjId());
		toObj.setSysCode(StringUtils.trimToEmpty(fromObj.getSysCode()));
		toObj.setExt1(StringUtils.trimToEmpty(fromObj.getExt1()));
		toObj.setExt2(StringUtils.trimToEmpty(fromObj.getExt2()));
		toObj.setExt3(StringUtils.trimToEmpty(fromObj.getExt3()));
		toObj.setExt4(StringUtils.trimToEmpty(fromObj.getExt4()));
		toObj.setExt5(StringUtils.trimToEmpty(fromObj.getExt5()));

	}

	/**
	 * 将对象属性替换成数据库列
	 *
	 * @param property
	 *            参数
	 */
	private void replaceProperty(final Map<String, Object> property) {
		if (property != null) {
			if (property.containsKey("organLogicId")) {
				property.put("ORGAN_LOGIC_ID", property.get("organLogicId"));
				property.remove("organLogicId");
			}
			if (property.containsKey("title")) {
				property.put("MSG_TITLE", property.get("title"));
				property.remove("title");
			}
			if (property.containsKey("content")) {
				property.put("MSG_CONTENT", property.get("content"));
				property.remove("content");
			}
			if (property.containsKey("sendType")) {
				property.put("SEND_TYPE", property.get("sendType"));
				property.remove("sendType");
			}
			if (property.containsKey("userId")) {
				property.put("USER_ID", property.get("userId"));
				property.remove("userId");
			}
			if (property.containsKey("userName")) {
				property.put("USER_NAME", property.get("userName"));
				property.remove("userName");
			}
			if (property.containsKey("sendTime")) {
				property.put("SEND_TIME", property.get("sendTime"));
				property.remove("sendTime");
			}
			if (property.containsKey("type")) {
				property.put("MSG_TYPE", property.get("type"));
				property.remove("type");
			}
			if (property.containsKey("url")) {
				property.put("MSG_URL", property.get("url"));
				property.remove("url");
			}
			if (property.containsKey("objId")) {
				property.put("OBJ_ID", property.get("objId"));
				property.remove("objId");
			}
			if (property.containsKey("sysCode")) {
				property.put("SYS_CODE", property.get("sysCode"));
				property.remove("sysCode");
			}
			if (property.containsKey("updatePerson")) {
				property.put("UPDATE_PERSON", property.get("updatePerson"));
				property.remove("updatePerson");
			}
			if (property.containsKey("updateTime")) {
				property.put("UPDATE_TIME", property.get("updateTime"));
				property.remove("updateTime");
			}
			if (property.containsKey("ext1")) {
				property.put("EXT1", property.get("ext1"));
				property.remove("ext1");
			}
			if (property.containsKey("ext2")) {
				property.put("EXT2", property.get("ext2"));
				property.remove("ext2");
			}
			if (property.containsKey("ext3")) {
				property.put("EXT3", property.get("ext3"));
				property.remove("ext3");
			}
			if (property.containsKey("ext4")) {
				property.put("EXT4", property.get("ext4"));
				property.remove("ext4");
			}
			if (property.containsKey("ext5")) {
				property.put("EXT5", property.get("ext5"));
				property.remove("ext5");
			}

		}
	}
}